import React, { useEffect, useState } from 'react'
import { Button, PageHeader, Modal, Form, Input, message } from 'antd';
import moment from 'moment'
import E from 'wangeditor'
import { ArticleAddApi, ArticleSearchApi, ArticleUpdateApi } from '../utils/request/api'
import { useParams, useNavigate,  useLocation } from 'react-router-dom'
import './less/Edit.less'
// 文章编辑组件

let editor = null
export default function Edit() {
  const [content, setContent] = useState('')
  const [title, setTitle] = useState('')
  const [subTitle, setSubTitle] = useState('')

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const params = useParams()
  const navigate = useNavigate()
  const location = useLocation()

  const dealData = (res) =>{
    if(res.errCode === 0){
      message.success(res.message)
      setTimeout(()=>{
        // 跳回list页面
        navigate('/list')
      },1000)
    } else {
      message.error(res.message)
    }
  }
  // 对话框点击提交
  const handleOk = () => {
    // validateFields()校验字段
    form.validateFields().then((values) => {
      form.resetFields();// reset重置
      let { title, subTitle } = values
      // console.log('values',values);
      // 地址栏有id代码先要编辑一篇文章
      if (params.id) {
        // 更新文章的请求
        ArticleUpdateApi({title, subTitle, content, id:params.id}).then(res=>{
          // console.log('ArticleUpdateApi',res);
          dealData(res)
        })
      } else {
        // 添加文章的请求
        ArticleAddApi({title, subTitle, content}).then(res => {
          // console.log('ArticleAddApi', res);
          dealData(res)
        })
      }
    }).catch((info) => {
      // console.log('Validate Failed:', info);
    });
    setIsModalOpen(false)
  };

  useEffect(() => {
    editor = new E('#div1')
    editor.config.onchange = (newHtml) => {
      setContent(newHtml)
    }
    editor.create()
    // 根据地址栏id做请求
    if (params.id) {
      // console.log('params', params);
      ArticleSearchApi({ id: params.id }).then(res => {
        if (res.errCode === 0) {
          // console.log('ArticleSearchApi', res)
          let { title, subTitle, content } = res.data
          editor.txt.html(content) // 重新设置文本内容
          setTitle(title)
          setSubTitle(subTitle)
        }
      })
    }
    return () => {
      // 组件销毁时销毁编辑器
      editor.destroy()
    }
  }, [location.pathname, params])
  return (
    <div className='edit'>
      <PageHeader
        ghost={false}
        onBack={params.id ? () => window.history.back() : null}
        title="文章编辑"
        subTitle={"当前日期：" + moment(new Date()).format("YYYY-MM-DD")}
        extra={<Button key="1" type="primary" onClick={() => setIsModalOpen(true)}>提交文章</Button>}
      >
      </PageHeader>
      <div id="div1"></div>
      <Modal
        zIndex={99999}
        title="填写文章标题"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={() => { setIsModalOpen(false) }}
        okText="提交"
        cancelText="取消">
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
          initialValues={{ title: title, subTitle: subTitle }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请填写标题！' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="副标题"
            name="subTitle"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>

  )
}
